import json
import logging
from django.http import JsonResponse
from django.urls import resolve

logger = logging.getLogger(__name__)

class APIErrorMiddleware:
    """
    API错误处理中间件
    处理404错误，提供更有用的错误信息
    """
    
    def __init__(self, get_response):
        self.get_response = get_response
        
    def __call__(self, request):
        # 获取请求路径
        path = request.path_info
        
        # 只处理API请求
        if not path.startswith('/api/'):
            return self.get_response(request)
            
        try:
            # 尝试解析URL
            resolver_match = resolve(path)
            # URL存在，继续正常流程
            response = self.get_response(request)
            return response
        except Exception as e:
            # 只处理404错误
            if hasattr(e, 'status_code') and e.status_code == 404:
                logger.warning(f"API路径未找到: {path}, 正在尝试提供替代路径")
                
                # 为常见的API路径提供建议
                suggestions = []
                
                # 用户相关API建议
                if 'users' in path or 'user' in path:
                    suggestions.extend([
                        '/api/umm/users/',
                        '/api/users/',
                        '/api/umm/user/',
                        '/api/user/'
                    ])
                    
                # 考勤相关API建议
                if 'attendance' in path:
                    suggestions.append('/api/umm/attendance/')
                    
                # 客服人员相关API建议
                if 'service-staff' in path:
                    suggestions.append('/api/umm/users/service-staff/')
                
                # 返回JSON格式的404错误响应
                return JsonResponse({
                    'code': 404,
                    'message': f'API路径未找到: {path}',
                    'suggestions': suggestions
                }, status=404)
            
            # 其他错误，继续正常流程
            response = self.get_response(request)
            return response 